import axios from 'axios'
import {jwt} from "../utils/jwt.js";
import {ElNotification} from "element-plus";

// 携带cookie
// axios.defaults.withCredentials = import.meta.env.VITE_APP_SECURITY_TYPE === 'session';

// 不使用 @/utils/request, 因为登录时不需要添加请求头
const service = axios.create({
    withCredentials: import.meta.env.VITE_APP_SECURITY_TYPE === 'session',
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000 // request timeout
})

export default {
    login(data) {
        return service({
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            url: '/login',
            method: 'post',
            data
        }).then(res => {
            console.debug(res)
            jwt.login(res.data.data)
            ElNotification({
                title: '成功',
                message: '欢迎：' + jwt.user.username,
                type: 'success'
            })
            return  Promise.resolve(res.data)
        }).catch(error => {
            console.debug("login failed")
            console.debug(error)
            jwt.logout()
            // ElNotification({
            //     title: '失败',
            //     message: error.response.data?.message || error.message,
            //     type: 'error'
            // })
            return Promise.reject(error.response.data)
        })
    },
    logout() {
        return service({
            url: '/logout',
            method: 'get'
        })
    }
}